//
//  M1EditInformationVC.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/21.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1EditInformationVC.h"

@interface M1EditInformationVC ()<UITextViewDelegate>
{
    NSInteger Max_Num_TextView;
}
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UILabel *textViewPlaceHolder;
@property (nonatomic, strong) UILabel *number;

@end

@implementation M1EditInformationVC

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange:) name:UITextViewTextDidChangeNotification object:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = self.titleStr;
    
    [self m1_createRightBarButtonItem:@"保存" titleColor:m1_color(0x333333) action:@selector(m1_rightAction)];
    
    if ([self.titleStr isEqualToString:@"详细地址"]) {
        Max_Num_TextView = 20;
    }else{
        Max_Num_TextView = 300;
    }
    
    [self createTextView];
}


- (void) m1_rightAction{
    
    if ([_textView.text length] <= 0) {
        [M1Alert m1_alertWithTitle:nil message:[NSString stringWithFormat:@"请输入%@", self.titleStr]];
        return;
    }
    
    if (self.returnText) {
        self.returnText(self.textView.text);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - textViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    if ([textView.text length] == 0) {
        [_textViewPlaceHolder setHidden:NO];
    }else{
        [_textViewPlaceHolder setHidden:YES];
    }
    
    
}

-(void)textChange:(NSNotification *)note{
    
    //获取当前键盘类型
    UITextInputMode *mode = (UITextInputMode *)[UITextInputMode activeInputModes][0];
    
    //获取当前键盘语言
    NSString *lang = mode.primaryLanguage;
    
    //如果语言是汉语(拼音)
    if ([lang isEqualToString:@"zh-Hans"])
    {
        //取到高亮部分范围
        UITextRange *selectedRange = [self.textView markedTextRange];
        //取到高亮部分
        UITextPosition *position = [self.textView positionFromPosition:selectedRange.start offset:0];
        //如果取不到高亮部分,代表没有拼音
        if (!position){
            //当期超过最大限制时
            if (self.textView.text.length > Max_Num_TextView) {
                
                //对超出部分进行裁剪
                self.textView.text = [self.textView.text substringToIndex:Max_Num_TextView];
                
                //同时将下方提示label设置为0
                self.number.text = [NSString stringWithFormat:@"%ld/%ld", Max_Num_TextView, Max_Num_TextView];
//                [self createHintAlert:[NSString stringWithFormat:@"最多只能输入%ld个字!请您合理安排内容!", Max_Num_TextView]];
                
                [self changeTextColor];
                
            }
            
            //如果没超出,那么就计算字数
            self.number.text = [NSString stringWithFormat:@"%ld/%ld", [self.textView.text length], Max_Num_TextView];
            
            [self changeTextColor];
            
        }else{
            //表示还有高亮部分，暂不处理
        }
        
    }else{
        //如果语言不是汉语,直接计算
        if (self.textView.text.length > Max_Num_TextView) {
            
            self.textView.text = [self.textView.text substringToIndex:Max_Num_TextView];
            
            self.number.text = [NSString stringWithFormat:@"%ld/%ld", Max_Num_TextView, Max_Num_TextView];
//            [self createHintAlert:[NSString stringWithFormat:@"最多只能输入%ld个字!请您合理安排内容!", Max_Num_TextView]];
            
            [self changeTextColor];
        }
        
        self.number.text = [NSString stringWithFormat:@"%ld/%ld", [self.textView.text length], Max_Num_TextView];
        
        [self changeTextColor];
    }
}

// 停止编辑

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    // 不让输入表情
//    if ([textView isFirstResponder]) {
//        if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textView textInputMode] primaryLanguage]) {
//            [XPPromptTag showWithText:@"不支持Emoji表情"];
//            return NO;
//        }
//
//        if ([text isIncludingEmoji]) {
//            [XPPromptTag showWithText:@"不支持Emoji表情"];
//            return NO;
//        }
//    }
    
    return YES;
}

#pragma  mark - createUI
- (void) createTextView{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, m1_NAV_HEIGHT + 10, SCREENWIDTH, 200)];
    bgView.backgroundColor = m1_color(0xFFFFFF);
    [self.view addSubview:bgView];
    
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 5, SCREENWIDTH - 30, CGRectGetHeight(bgView.frame) - 45)];
    _textView.backgroundColor = m1_color(0xFFFFFF);
    _textView.text = self.textStr;
    _textView.textColor = m1_color(0x666666);
    _textView.font = m1_font(15);
    _textView.delegate = self;
    _textView.returnKeyType = UIReturnKeyDone;
    [bgView addSubview:_textView];
    
    
    self.textViewPlaceHolder = [[UILabel alloc]initWithFrame:CGRectMake(6, 6, CGRectGetWidth(_textView.frame), 20)];
    _textViewPlaceHolder.enabled = NO;
    _textViewPlaceHolder.text = [NSString stringWithFormat:@"请输入%@", _titleStr];
    _textViewPlaceHolder.font = m1_font(15);
    _textViewPlaceHolder.textColor = m1_color(0x999999);
    [self.textView addSubview:_textViewPlaceHolder];
    if ([_textStr length] > 0) {
        [_textViewPlaceHolder setHidden:YES];
    }
    
    self.number = [[UILabel alloc] initWithFrame:CGRectMake(SCREENWIDTH - 80, CGRectGetMaxY(_textView.frame) + 5, 60, 30)];
    _number.text = [NSString stringWithFormat:@"%ld/%ld", [self.textStr length], Max_Num_TextView];
    _number.textColor = m1_color(0x333333);
    _number.font = m1_font(14);
    _number.textAlignment = NSTextAlignmentRight;
    [bgView addSubview:_number];
    [self changeTextColor];
    
}

- (void) changeTextColor{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:_number.text];
    NSRange range=[[attributedString string] rangeOfString:[NSString stringWithFormat:@"/%ld", Max_Num_TextView]];
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:m1_color(0x333333) range:range];
    [_number setAttributedText:attributedString];
}


- (void) m1_createRightBarButtonItem:(NSString *)title titleColor:(UIColor *)color action:(SEL)action{
    CGFloat width;
    if ([title length] > 2) {
        width = 70;
    }else{
        width = 40;
    }
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, width, 44);
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    button.titleLabel.font = m1_font(16);
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBtn = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightBtn;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
